<template>
  <div class="car-verify-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>用车合规性验证</span>
      </div>
      
      <el-form :model="carForm" :rules="carRules" ref="carFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="userName">
              <el-input v-model="carForm.userName" placeholder="请输入员工姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="carForm.department" placeholder="请选择部门">
                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="carNumber">
              <el-input v-model="carForm.carNumber" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用车日期" prop="useDate">
              <el-date-picker
                v-model="carForm.useDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起始里程" prop="startMileage">
              <el-input v-model.number="carForm.startMileage" placeholder="请输入起始里程">
                <template slot="append">公里</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终止里程" prop="endMileage">
              <el-input v-model.number="carForm.endMileage" placeholder="请输入终止里程">
                <template slot="append">公里</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行驶里程" prop="travelMileage">
              <el-input v-model="travelMileage" disabled>
                <template slot="append">公里</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报销金额" prop="amount">
              <el-input v-model="carForm.amount" placeholder="请输入报销金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="用车事由" prop="reason">
          <el-input v-model="carForm.reason" type="textarea" placeholder="请输入用车事由"></el-input>
        </el-form-item>
        
        <el-form-item label="行车路线" prop="route">
          <el-input v-model="carForm.route" type="textarea" placeholder="请输入行车路线"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交验证</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 验证结果对话框 -->
    <el-dialog title="验证结果" :visible.sync="verifyDialogVisible" width="60%">
      <div v-loading="verifying">
        <div v-if="!verifying && verifyResult">
          <el-result
            :icon="verifyResult.pass ? 'success' : 'error'"
            :title="verifyResult.pass ? '验证通过' : '验证不通过'"
            :sub-title="verifyResult.message">
          </el-result>
          
          <el-divider content-position="center">详细验证结果</el-divider>
          
          <el-descriptions title="合规性验证结果" :column="1" border>
            <el-descriptions-item label="里程连续性检查">
              <el-tag :type="verifyResult.mileageContinuity ? 'success' : 'danger'">
                {{ verifyResult.mileageContinuity ? '通过' : '不通过' }}
              </el-tag>
              <div v-if="!verifyResult.mileageContinuity" class="error-detail">
                {{ verifyResult.mileageContinuityMessage }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="金额计算准确性">
              <el-tag :type="verifyResult.amountAccuracy ? 'success' : 'danger'">
                {{ verifyResult.amountAccuracy ? '通过' : '不通过' }}
              </el-tag>
              <div v-if="!verifyResult.amountAccuracy" class="error-detail">
                {{ verifyResult.amountAccuracyMessage }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="出差时间冲突检查">
              <el-tag :type="verifyResult.travelConflict ? 'danger' : 'success'">
                {{ verifyResult.travelConflict ? '存在冲突' : '无冲突' }}
              </el-tag>
              <div v-if="verifyResult.travelConflict" class="error-detail">
                {{ verifyResult.travelConflictMessage }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="验证结论">
              {{ verifyResult.conclusion }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="verifyDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSaveResult" :disabled="verifying || !verifyResult">保存结果</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CarVerify',
  data() {
    // 自定义验证终止里程必须大于起始里程
    const validateEndMileage = (rule, value, callback) => {
      if (value <= this.carForm.startMileage) {
        callback(new Error('终止里程必须大于起始里程'))
      } else {
        callback()
      }
    }
    
    return {
      loading: false,
      carForm: {
        userName: '',
        department: '',
        carNumber: '',
        useDate: '',
        startMileage: '',
        endMileage: '',
        amount: '',
        reason: '',
        route: ''
      },
      carRules: {
        userName: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        carNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5}$/, message: '请输入正确的车牌号格式', trigger: 'blur' }
        ],
        useDate: [
          { required: true, message: '请选择用车日期', trigger: 'change' }
        ],
        startMileage: [
          { required: true, message: '请输入起始里程', trigger: 'blur' },
          { type: 'number', message: '里程必须为数字', trigger: 'blur' }
        ],
        endMileage: [
          { required: true, message: '请输入终止里程', trigger: 'blur' },
          { type: 'number', message: '里程必须为数字', trigger: 'blur' },
          { validator: validateEndMileage, trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入报销金额', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请输入用车事由', trigger: 'blur' }
        ],
        route: [
          { required: true, message: '请输入行车路线', trigger: 'blur' }
        ]
      },
      departmentOptions: [
        { value: '财务部', label: '财务部' },
        { value: '人力资源部', label: '人力资源部' },
        { value: '市场部', label: '市场部' },
        { value: '技术部', label: '技术部' },
        { value: '运营部', label: '运营部' }
      ],
      verifyDialogVisible: false,
      verifying: false,
      verifyResult: null
    }
  },
  computed: {
    // 计算行驶里程
    travelMileage() {
      if (this.carForm.startMileage && this.carForm.endMileage) {
        const start = Number(this.carForm.startMileage)
        const end = Number(this.carForm.endMileage)
        if (!isNaN(start) && !isNaN(end) && end > start) {
          return (end - start).toFixed(2)
        }
      }
      return ''
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.carFormRef.validate(async valid => {
        if (!valid) return
        
        this.loading = true
        this.verifyDialogVisible = true
        this.verifying = true
        this.verifyResult = null
        
        // 模拟验证过程
        setTimeout(() => {
          // 计算预期金额
          const mileage = Number(this.carForm.endMileage) - Number(this.carForm.startMileage)
          const expectedAmount = (mileage * 0.6).toFixed(2) // 假设单价为0.6元/公里
          const actualAmount = Number(this.carForm.amount)
          
          // 模拟上次里程记录
          const lastEndMileage = Number(this.carForm.startMileage) - Math.floor(Math.random() * 1000)
          
          // 随机生成验证结果
          const mileageContinuity = Math.random() > 0.2
          const amountAccuracy = Math.abs(actualAmount - expectedAmount) < 0.01
          const travelConflict = Math.random() > 0.8
          
          this.verifyResult = {
            pass: mileageContinuity && amountAccuracy && !travelConflict,
            message: mileageContinuity && amountAccuracy && !travelConflict ? 
              '私车公用报销申请验证通过' : '私车公用报销申请验证不通过',
            mileageContinuity,
            mileageContinuityMessage: mileageContinuity ? 
              '' : `当前起始里程(${this.carForm.startMileage})小于上次记录的终止里程(${lastEndMileage})`,
            amountAccuracy,
            amountAccuracyMessage: amountAccuracy ? 
              '' : `金额计算不准确，行驶里程${mileage}公里，单价0.6元/公里，应为${expectedAmount}元，实际报销${actualAmount}元`,
            travelConflict,
            travelConflictMessage: travelConflict ? 
              `该用户在${this.carForm.useDate}有出差记录，与私车公用时间冲突` : '',
            conclusion: mileageContinuity && amountAccuracy && !travelConflict ? 
              '该私车公用申请符合规定，可以报销' : '该私车公用申请存在异常，不建议报销'
          }
          
          this.verifying = false
          this.loading = false
        }, 2000)
        
        // 实际项目中应该是这样的API调用
        // try {
        //   const { data } = await this.$http.post('/car/verify', this.carForm)
        //   if (data.code === 0) {
        //     this.verifyResult = data.data
        //   } else {
        //     this.$message.error(data.message || '验证失败')
        //   }
        // } catch (error) {
        //   this.$message.error('验证失败')
        // } finally {
        //   this.verifying = false
        //   this.loading = false
        // }
      })
    },
    
    // 保存验证结果
    handleSaveResult() {
      this.$message.success('验证结果已保存')
      this.verifyDialogVisible = false
      this.resetForm()
      
      // 实际项目中应该是这样的API调用
      // try {
      //   await this.$http.post('/car/save-result', {
      //     carForm: this.carForm,
      //     result: this.verifyResult
      //   })
      //   this.$message.success('验证结果已保存')
      //   this.verifyDialogVisible = false
      //   this.resetForm()
      // } catch (error) {
      //   this.$message.error('保存结果失败')
      // }
    },
    
    // 重置表单
    resetForm() {
      this.$refs.carFormRef.resetFields()
    }
  }
}
</script>

<style scoped>
.car-verify-container {
  padding: 20px 0;
}

.error-detail {
  margin-top: 5px;
  color: #F56C6C;
  font-size: 12px;
}
</style> 